package app.server;

import app.server.handlers.HttpPerfHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

@Component
@Primary
public class MyServer {
    @Value("${server.host:0.0.0.0}") String host;
    @Value("${server.port:8000}") int port;

    @Autowired
    private ApplicationContext applicationContext;

    @Value("${epoll:false}")
    boolean epoll;

    @Autowired
    private org.springframework.beans.factory.BeanFactory beanFactory;

    public void start(){
        EventLoopGroup bossGroup = epoll? new EpollEventLoopGroup(1) : new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = epoll? new EpollEventLoopGroup() : new NioEventLoopGroup();
        Class serverSocketChannel = epoll? EpollServerSocketChannel.class : NioServerSocketChannel.class;
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.option(ChannelOption.SO_BACKLOG, 1024);
            b.group(bossGroup, workerGroup)
                    .channel(serverSocketChannel)
                    .childHandler(new ChannelInitializer<SocketChannel>(){
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            // 确保bean的多实例实现
                            HttpPerfHandler perfHandler = applicationContext.getBean(HttpPerfHandler.class);
                             ch.pipeline()
                            .addLast(new HttpServerCodec())
                            .addLast(perfHandler);
                        }
                    });

            Channel ch = b.bind(host,port).sync().channel();
            System.out.println("app started @"+host+":"+port);
            ch.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
